// pages/org/org.js
const app = getApp()
var service = require('../../util/service')
var util = require('../../util/util')
var QRCode = require('../../util/weapp-qrcode.js')
var qrcode;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    org:{},
    imgurl: service.imgurl,
    id:"",
    zan:{
      state:false,
      icon:"../../images/photo/zan.png"
    },
    comment: {
      state: false,
      icon: "../../images/photo/comment.png"
    },
    collection: {
      state: false,
      icon: "../../images/photo/collection.png"
    },
    coupons:[],
    showModal:false,
    qrcodeShow:false,
    plnum:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    console.log(app);
    
    var user = app.userInfo;
    var id = options.id;
    service.AJAX("smc/base/SystemProviderUser/findSystemProviderUser.json", { id: options.id}, res => {
      console.log(res);
      res.imgs = res.pic && res.pic.split(",");
      for (var i = 0; i < res.imgs.length;i++){
        res.imgs[i] = service.imgurl +res.imgs[i];
      }
      this.setData({
        org: res,
        id: options.id
      })
      var lookNumber = res.lookNumber || 0;
      var norg = {
        prvId: res.prvId,
        lookNumber: lookNumber+1
      }
      if (res.attribute4 == 'XS') {
        qrcode = new QRCode('canvas', {
          text: "code=0000000000000",
          width: 150,
          height: 150,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.H,
        });
      }
      //统计评论数量
      service.AJAX(`smc/topic/BasicComments/groupBasicComments.json?$group-additions=count-1&$relId=${id}&$relType=Provider`, {}, res => {
        this.setData({
          plnum: res
        });
      }, err => { }, 'POST')
      //更新org的浏览量
      service.AJAX(`smc/base/SystemProviderUser/updSystemProviderUser.do`, norg, res => { }, err => { }, "POST");
      //判断是否有浏览历史 如有则不增加 如没有则增加
      service.AJAX(`smc/topic/LookHistory/listLookHistory.json?$relType=Provider&$relId=${options.id}&$userId=${user.buyId}`, {}, res => {
        if (res.length <= 0){
          var LookHistory = {
            title: options.title,
            relType:'Provider',
            relId: options.id,
            userId: user.buyId
          }
          service.AJAX("smc/topic/LookHistory/addLookHistory.do", LookHistory, res => {
          }, err => { }, 'POST')
        }
      }, err => { }, 'GET', true)
      service.AJAX("smc/base/SystemProduct/listSystemProduct.json", { "$prvId": options.id}, res => {
        console.log(res);
        var porg = this.data.org;
        porg.course = res;
        this.setData({
          org: porg
        })
      }, err => { }, 'GET',true)
      //获取点赞集合判断用户是否对改机构进行过点赞
      service.AJAX(`smc/dim/RecordPraiseRel/listRecordPraiseRel.json?$relType=Provider&$relId=${options.id}&$userId=${user.buyId}`, {}, res => {
        if(res.length > 0){
          this.setData({
            zan: { state: true, icon: "../../images/photo/zans.png"}
          });
        }
      }, err => { }, 'GET', true)
      //通过用户收藏字段判断用户是否对该机构进行过收藏
      //{provider:"12,34,56",topic:"11,22,33"}格式
      var buyc = user.buyCollection;
      if (buyc && buyc != "" && buyc != "null"){
        var buyobj = JSON.parse(buyc); 
        if (buyobj){
          var provc = buyobj.provider;
          var len = (","+options.id).length;
          //标示以收藏
          if (provc && provc.length > 0 && (provc.indexOf(options.id + ",") == 0 || provc.indexOf("," + options.id + ",") >= 0 || provc.indexOf("," + options.id) == (provc.length - len))){
            this.setData({
              collection: { state: true, icon:"../../images/photo/collections.png"}
            });
          }
        }
      }

      //加载机构是否有优惠卷 如有显示优惠卷图标
      //先获取用户所有优惠卷信息 对比现有优惠卷确定是否可领取
      service.AJAX(`smc/buy/CouponRecipients/listCouponRecipients.json?$userId=${user.buyId}`, {}, res => {
        var res2 = res || [];
        service.AJAX(`smc/buy/CouponVoucher/listCouponVoucher.json?$relType=Provider&$relId=${options.id}`, {}, res => {
          var res = res || [];
          for (var i = 0; i < res.length; i++) {
            res[i].effeDateFrom = util.getDate(res[i].effeDateFrom);
            res[i].effeDateEnd = util.getDate(res[i].effeDateEnd);
            res[i].btnstate = 1;
            for (var j = 0; j < res2.length;j++){
              if (res2[j].voucherId == res[i].couponId){
                res[i].btnstate = 0;
                break;
              }
            }
          }
          this.setData({
            coupons: res
          });
        }, err => { }, 'GET', true)
      }, err => { }, 'GET', true)
      
    }, err => { }, 'POST')
    
  },
  tapqrcode:function(){
    this.setData({
      qrcodeShow: false
    })
  },
  tapHandler:function(e){
    qrcode.makeCode(e.target.dataset.code);
    this.setData({
      qrcodeShow: true
    })
  },
  previewImg: function (e) {
    var index = 0;
    var imgArr = this.data.org.imgs;
    wx.previewImage({
      current: imgArr[index],     //当前图片地址
      urls: imgArr,               //所有要预览的图片的地址集合 数组形式
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })

    
  },
  makePhone:function(){
    wx.makePhoneCall({
      phoneNumber: this.data.org.mobile,
      success: function () {
        console.log("拨打电话成功！");
      },
      fail: function () {
        console.log("拨打电话失败！");
      }
    })
  },
  navigation:function(){
    var $this = this;
    var data = $this.data.org;
    if (data.posX != "" && data.posY != "") {
      wx.openLocation({
        longitude: parseFloat(data.posY),
        latitude: parseFloat(data.posX),
        name: data.prvName,
        address: data.addrDetail,
        scale: 28
      })
    }
  },
  zans:function(){
    var zan = this.data.zan;
    zan.state = !zan.state;
    //获取点赞集合判断用户是否对改机构进行过点赞
    service.AJAX2(`smc/dim/RecordPraiseRel/dealRecordPraiseRel.do`, { relId: this.data.id, userId: app.userInfo.buyId, relType:'Provider'}, res => {
      if (res > 0){
        var title = "";
        var org = this.data.org;
        if (zan.state) {
          zan.icon = "../../images/photo/zans.png";
          title = "点赞成功";
          org.thumbsNumber = org.thumbsNumber +1;
        } else {
          zan.icon = "../../images/photo/zan.png";
          title = "取消点赞成功";
          org.thumbsNumber = org.thumbsNumber -1;
        }
        wx.showToast({
          title: title,
          icon: 'succes',
          duration: 1000,
          mask: true
        })
        this.setData({
          zan: zan,
          org: org
        });
      }else{
        wx.showToast({
          title: "系统异常请稍后再试",
          icon: 'error',
          duration: 1000,
          mask: true
        })
      }
    }, err => { }, 'GET', true)
  },
  collections: function () {
    var collection = this.data.collection;
    collection.state = !collection.state;
    var title = "";
    var user = app.userInfo;
    var buyc = (user.buyCollection && user.buyCollection != "null") ? user.buyCollection: "{}";
    var buyobj = JSON.parse(buyc);
    var provider = buyobj.provider || "";
    var buycs = provider.split(",");
    var org = this.data.org;
    var a3 = parseInt(org.attribute3 || 0);
    if (collection.state) {
      collection.icon = "../../images/photo/collections.png";
      title = "收藏成功";
      buycs.push(this.data.id);
      org.attribute3 = a3 + 1
    } else {
      collection.icon = "../../images/photo/collection.png";
      title = "取消收藏成功";
      var newbuycs = [];
      for (var i = 0; i < buycs.length;i++){
        if (buycs[i] != this.data.id) newbuycs.push(buycs[i]);
      }
      buycs = newbuycs;
      org.attribute3 = a3 - 1
    }
    wx.showToast({
      title: title,
      icon: 'succes',
      duration: 1000,
      mask: true
    })
    buyobj.provider = buycs.toString();
    user.buyCollection = JSON.stringify(buyobj);
    var nuser = {
      buyId: user.buyId,buyCollection: user.buyCollection};
    //更新用户收藏项
    service.AJAX(`smc/base/SystemBuyerUser/updSystemBuyerUser.do`, nuser, res => {}, err => { }, "POST");
    org.attribute3 = org.attribute3 + "";
    var norg = {
      prvId: org.prvId,
      attribute3: org.attribute3
    }
    
    //更新org的收藏数
    service.AJAX(`smc/base/SystemProviderUser/updSystemProviderUser.do`, norg, res => { }, err => { }, "POST");
    this.setData({
      collection: collection,
      org: org
    });
  },
  comments: function () {
    var comment = this.data.comment;
    comment.state = !comment.state;
    if (comment.state) {
      comment.icon = "../../images/photo/comments2.png";
    }else{
      comment.icon = "../../images/photo/comment.png";
    }
    this.setData({
      comment: comment
    });
    wx.navigateTo({
      url: `../comment/comment?type=Provider&id=${this.data.org.prvId}`
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  coupon1:function(){
    wx.showToast({
      title: "领取成功",
      icon: 'succes',
      duration: 1000,
      mask: true
    })
  },
  coupon2: function () {
    this.setData({
      showModal: true
    });
  },
 
  hideModal:function(){
    this.setData({
      showModal: false
    });
  },
  getcoupon: function (item){
    var data = item.currentTarget.dataset;
    var tid = data.tid;
    var recip = {
      used: false,
      voucherId: tid,
      userId: app.userInfo.buyId
    }
    service.AJAX("smc/buy/CouponRecipients/addCouponRecipients.do", recip, res => {
      wx.showToast({
        title: "领取成功",
        icon: 'succes',
        duration: 1000,
        mask: true
      })
      var coupons = this.data.coupons;
      for (var i = 0; i < coupons.length; i++) {
        if (tid == coupons[i].couponId) {
          coupons[i].btnstate = 0;
          break;
        }
      }
      this.setData({
        coupons: coupons
      });

    }, err => { }, 'POST')
  }
})